package com.nt.thah.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @Description: 二维码工具类
 * @Author ls
 * @Date 2021/08/09 15:45
 */
public class QRCodeUtil {

    /**
     * @Description: 生成二维码并上传oss
     * @Author ls
     * @Date 2021/08/09 15:45
     */
    public static String createImage(String url, int productId) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        int width = 430, height = 430;
        BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
//        MatrixToImageWriter.writeToPath(bitMatrix, "PNG",
//                FileSystems.getDefault().getPath("d:\\test.png"));
        OSS instance = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com", "LTAI4G8ct17ymvoo91fyPVoZ", "LKMSaIEvyFVFOg2vz5oCKtI5xNXJs6");
        String key = "product/" + productId + "/" + System.currentTimeMillis() + ".png";
        instance.putObject("tyqf-bucket", key, inputStream);
        return key;
    }

}
